//
//  YWLedgerViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/4/20.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWLedgerViewController.h"
#import "YWSelectBuildingTableViewController.h"
#import "YWMatchMissionsViewController.h"
#import "YWPostTroubleTableViewController.h"
#import "YWNoQrcodeLedgerLocationDetailViewController.h"
#import "YWCreateTempMissionTableViewController.h"
#import "YWLedgerEquListTableViewController.h"

#import "UIColor+CustomColors.h"
#import "MBProgressHUD.h"
#import "DOPDropDownMenu.h"
#import "UIScrollView+EmptyDataSet.h"
#import "MJRefresh.h"
#import "YWCommonTool.h"
#import "BHBPopView.h"

#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWEquipmentManager.h"
#import "YWEquipment.h"
#import "YWEquipmentType.h"
#import "YWInspectionMissionManager.h"
#import "YWNotifyManager.h"
#import "YWLoginTool.h"
#import "YWNoQrcodeLocationCellModel.h"
#import "YWMissionManager.h"
#import "YWFunctionModel.h"
#import "YWFunctionManager.h"

#import "YWNoQrcodeLedgerLocationTableViewCell.h"
#import "YWLedgerEquTypeTotalCell.h"

@interface YWLedgerViewController ()<DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,YWSelectBuildingTableViewControllerDelegate,YWNoQrcodeLedgerLocationTableViewCellDelegate,YWLedgerEquTypeTotalCellDelegate>

@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIButton *headButton;

@property (nonatomic, strong) NSMutableArray *currentDataSource;
@property (nonatomic, strong) NSMutableArray *tableViewDataSource;

@property (nonatomic, strong) NSMutableArray *buildingArray;
@property (nonatomic, strong) NSMutableArray *apartmentArray;
@property (nonatomic, strong) NSMutableArray * floorArray;
@property (nonatomic, strong) NSMutableArray *locationArray;
@property (nonatomic, strong) NSMutableArray *equipmentTypeArray;
//当前显示地址
@property (nonatomic, strong) YWBuilding * currentBuilding;
@property (nonatomic, strong) YWApartment * currentApartment;
@property (nonatomic, strong) YWFloor * currentFloor;
@property (nonatomic, strong) YWLocation * currentLocation;
@property (nonatomic, strong) YWEquipmentType * currentEquipmentType;
@property (nonatomic, strong) YWNoQrcodeLocationCellModel * locationModel;
@end

@implementation YWLedgerViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.title = @"设备台账";
    [self rightBarButton];
    [self defaultData];
    if (_currentDataSource.count) {
        [self.menu selectDefalutIndexPath];
    }
    [self setupNotification];
    [self setupTableView];
    [self setupCurrentModel];
}

- (void)rightBarButton{
    if (self.locationId) {
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:self.locationId];
    }else if (self.qrcodeId){
        NSInteger locationId = self.qrcodeId?[[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.qrcodeId]:0;
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
    }
    if (_currentBuilding == nil) {
        _currentBuilding = self.buildingArray.count ? self.buildingArray[0] : nil;
    }
    NSString * buttonTitle = _currentBuilding.buildingName;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:buttonTitle style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
}

- (void)setupTableView{
    [self.tableView registerClass:[YWNoQrcodeLedgerLocationTableViewCell class] forCellReuseIdentifier:YWNoQrcodeLedgerLocationTableViewCellIdentifier];
    [self.tableView registerClass:[YWLedgerEquTypeTotalCell class] forCellReuseIdentifier:YWLedgerEquTypeTotalCellIdentifier];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.sectionFooterHeight = 0.01f;
    self.tableView.tableHeaderView = _menu;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)defaultData{
    _currentApartment = self.apartmentArray.count ? self.apartmentArray[0] : nil;
    _currentFloor = self.floorArray.count ? self.floorArray[0] : nil;
    _currentLocation = self.locationArray.count ? self.locationArray[0] : nil;
    _currentEquipmentType = self.equipmentTypeArray.count ? self.equipmentTypeArray[0] : nil;
    if (self.buildingArray.count) {
        _currentDataSource = [NSMutableArray arrayWithObjects:self.apartmentArray,self.floorArray,self.locationArray,self.equipmentTypeArray,nil];
    }
}

- (void)setupNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMatchMissions) name:KRefreshInspectionTimeLineNotification object:nil];
    [[YWNotifyManager shareManager] addReflashPatrolLineViewObserver:self selector:@selector(refreshMatchMissions)];
    [[YWNotifyManager shareManager] addMissionFinishedObserver:self selector:@selector(refreshMatchMissions)];
}

- (void)setupCurrentModel{
    if (self.qrcodeId) {
        //扫码的当前位置
        YWLocation *currentLocation = [[YWLocation alloc] init];
        NSInteger locationId = self.qrcodeId?[[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.qrcodeId]:0;
        YWLocation* location = [[YWBuildingManager shareManager] locationWithId:locationId];
        currentLocation.locationName = location.locationName;
        currentLocation.locationId = locationId;
        _currentLocation = currentLocation;
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
        //当前位置下的设备类型
        _equipmentTypeArray = [self equipmentTypes];
        [_currentDataSource replaceObjectAtIndex:_currentDataSource.count-1 withObject:_equipmentTypeArray];
        //给model赋值
        [self setUpModel:self.qrcodeId];
    }else if (self.locationId){
        YWLocation* location = [[YWBuildingManager shareManager] locationWithId:self.locationId];
        _currentLocation = location;
        _currentFloor = [[YWBuildingManager shareManager] floorWithId:location.floorId];
        _currentApartment = [[YWBuildingManager shareManager] apartmentWithId:_currentFloor.apartmentId];
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:self.locationId];
        //当前位置下的设备类型
        _equipmentTypeArray = [self equipmentTypes];
        [_currentDataSource replaceObjectAtIndex:_currentDataSource.count-1 withObject:_equipmentTypeArray];
        [self refreshMatchMissions];
        [self goSelect];
    }else{
        [self setUpModel:nil];
    }
}

#pragma mark --- DOPDropDownMenuDelegate
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return _currentDataSource.count;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    return column<0 ? 0 : [_currentDataSource[column] count];
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0){
        YWApartment *apartment = _currentDataSource[indexPath.column][indexPath.row];
        return apartment.apartmentName;
    }else if (indexPath.column == 1){
        YWFloor *floor = _currentDataSource[indexPath.column][indexPath.row];
        return floor.floorName;
    }else if (indexPath.column == 2){
        YWLocation *location = _currentDataSource[indexPath.column][indexPath.row];
        return location.locationName;
    }else{
        YWEquipmentType * equipmentType = _currentDataSource[indexPath.column][indexPath.row];
        return equipmentType.equipmentTypeName;
    }
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
    BOOL needSelect = NO;
    if (indexPath.column == 0){
        YWApartment *apartment = _currentDataSource[indexPath.column][indexPath.row];
        if (self.currentApartment.apartmentId != apartment.apartmentId) {
            needSelect = YES;
            self.currentApartment = apartment;
            _currentFloor = nil;
            _currentLocation = nil;
            _currentEquipmentType = nil;
            NSMutableArray *floorMut = [NSMutableArray array];
            YWFloor * floor = [[YWFloor alloc] init];
            NSString *floorShowName = [YWLoginTool floorShowName];
            floor.floorName = floorShowName.length? floorShowName:@"楼层";
            [floorMut addObject:floor];
            NSArray *floorArrays = [[YWBuildingManager shareManager] floorWithApartmentId:_currentApartment.apartmentId];
            [floorMut addObjectsFromArray:floorArrays];
            _currentFloor = floorMut[0];
            [_currentDataSource replaceObjectAtIndex:1 withObject:floorMut];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:1 row:0];
            [_menu selectIndexPath:reloadIndexPath];
            reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
    }else if (indexPath.column == 1){
        YWFloor *floor = _currentDataSource[indexPath.column][indexPath.row];
        if (self.currentFloor.floorId != floor.floorId) {
            needSelect = YES;
            self.currentFloor = floor;
            _currentLocation = nil;
            _currentEquipmentType = nil;
            NSMutableArray *locationMut = [NSMutableArray array];
            YWLocation * location = [[YWLocation alloc] init];
            NSString *locationShowName = [YWLoginTool locationShowName];
            location.locationName = locationShowName.length? locationShowName:@"位置";
            [locationMut addObject:location];
            NSArray *locationArrays = [[YWBuildingManager shareManager] locationWithFloorId:_currentFloor.floorId];
            [locationMut addObjectsFromArray:locationArrays];
            [_currentDataSource replaceObjectAtIndex:2 withObject:locationMut];
            DOPIndexPath *reloadIndexPathLocation = [DOPIndexPath indexPathWithCol:2 row:0];
            [_menu selectIndexPath:reloadIndexPathLocation];
        }
    }else if (indexPath.column == 2){
        YWLocation *location = _currentDataSource[indexPath.column][indexPath.row];
        if (self.currentLocation.locationId != location.locationId) {
            needSelect = YES;
            self.currentLocation = location;
            _equipmentTypeArray = nil;
            NSMutableArray *equipmentTypeMut = [NSMutableArray array];
            YWEquipmentType * equipmentType = [[YWEquipmentType alloc] init];
            equipmentType.equipmentTypeName = [NSString stringWithFormat:@"设备类型"];
            [equipmentTypeMut addObject:equipmentType];
            
            NSArray * typeArray = [[YWEquipmentManager shareManager] equipmentTypesWithLocationId:_currentLocation.locationId orBuildingId:_currentBuilding.buildingId];
            [equipmentTypeMut addObjectsFromArray:typeArray];
            [_currentDataSource replaceObjectAtIndex:3 withObject:equipmentTypeMut];
            DOPIndexPath *reloadIndexPathEquipment = [DOPIndexPath indexPathWithCol:3 row:0];
            [_menu selectIndexPath:reloadIndexPathEquipment];
        }
    }else{
        needSelect = YES;
        YWEquipmentType *equipmentType = _currentDataSource[indexPath.column][indexPath.row];
        _currentEquipmentType = equipmentType?:nil;
    }
    if (needSelect) {
        //这里把二维码置空，是为了匹配任务不再是按照二维码匹配，而是按照位置匹配
        _qrcodeId = nil;
        _locationId = 0;
        [self refreshMatchMissions];
        [self goSelect];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1+self.tableViewDataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YWNoQrcodeLedgerLocationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerLocationTableViewCellIdentifier];
        cell.locationModel = self.locationModel;
        cell.delegate = self;
        return cell;
    }
    else{
        YWLedgerEquTypeTotalCell * cell = [tableView dequeueReusableCellWithIdentifier:YWLedgerEquTypeTotalCellIdentifier];
        cell.equipmentInfo = self.tableViewDataSource[indexPath.section-1];
        cell.delegate = self;
        return cell;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        if (self.matchMissions.count) {
            if (!_headView) {
                _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+kTopPadding*3)];
            }
            if (!_headButton) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                [button setFrame:CGRectMake(50, kTopPadding*2, SCREEN_WIDTH-100, kButtonH)];
                button.titleLabel.font = kBoldContentFont;
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                button.clipsToBounds = YES;
                button.layer.cornerRadius = 4.0;
                [button addTarget:self action:@selector(clickHeadViewButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
                _headButton = button;
            }
            [self setUpButton:_headButton];
            
            [_headView addSubview:_headButton];
            return _headView;
        }else{
            [_headButton removeFromSuperview];
            return nil;
        }
    }else{
        static NSString* HeaderIdentifier = @"YWLedgerViewControllerForHeaderInSection";
        
        UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
        if (headerView == nil) {
            headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
            headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
            UILabel* label = [[UILabel alloc] init];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor customTextGrayColor];
            label.tag = 1009;
            label.numberOfLines = 0;
            label.font = KTitleFont;
            [headerView addSubview:label];
        }
        NSString *headText = [self tableViewHeadTxt:section];
        UILabel* label = [headerView viewWithTag:1009];
        label.text = headText;
        label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 30);
        return headerView;
    }
}

-(NSString *)tableViewHeadTxt:(NSInteger)section{
    if (section == 1) {
        if (self.tableViewDataSource.count) {
            return @"设备统计";
        }else{
            return @"";
        }
    }else{
        return @"";
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        if (self.matchMissions.count) {
            return kButtonH+kTopPadding*3;
        }else{
            return 0;
        }
    }else if (section == 1){
        return 30;
    }else{
        return 10;
    }
}

#pragma mark----懒加载
- (DOPDropDownMenu *)menu{
    if (!_menu) {
        DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];
        menu.delegate = self;
        menu.dataSource = self;
        _menu = menu;
    }
    return _menu;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = @"查询中";
        hud.dimBackground = YES;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (NSMutableArray *)buildingArray{
    if (!_buildingArray) {
        NSArray *allBuilding = [[YWBuildingManager shareManager] allBuilding];
        _buildingArray = [NSMutableArray array];
        [_buildingArray addObjectsFromArray:allBuilding];
    }
    return _buildingArray;
}

- (NSMutableArray *)apartmentArray{
    if (!_apartmentArray) {
        NSArray *allApartment = [[YWBuildingManager shareManager] apartmentWithbuildingId:self.currentBuilding.buildingId];
        _apartmentArray = [NSMutableArray array];
        YWApartment *apartment = [[YWApartment alloc] init];
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartment.apartmentName = apartmentShowName.length? apartmentShowName:@"楼栋";
        [_apartmentArray addObject:apartment];
        [_apartmentArray addObjectsFromArray:allApartment];
    }
    return _apartmentArray;
}

- (NSMutableArray *)floorArray{
    if (!_floorArray) {
        NSArray *allFloor = [[YWBuildingManager shareManager] floorWithApartmentId:self.currentApartment.apartmentId];
        _floorArray = [NSMutableArray array];
        YWFloor *floor = [[YWFloor alloc] init];
        NSString *floorShowName = [YWLoginTool floorShowName];
        floor.floorName = floorShowName.length? floorShowName:@"楼层";
        [_floorArray addObject:floor];
        [_floorArray addObjectsFromArray:allFloor];
    }
    return _floorArray;
}

- (NSMutableArray *)locationArray{
    if (!_locationArray) {
        NSArray *allLocation = [[YWBuildingManager shareManager] locationWithFloorId:self.currentFloor.floorId];
        _locationArray = [NSMutableArray array];
        YWLocation *location = [[YWLocation alloc] init];
        NSString *locationShowName = [YWLoginTool locationShowName];
        location.locationName = locationShowName.length? locationShowName:@"位置";
        [_locationArray addObject:location];
        [_locationArray addObjectsFromArray:allLocation];
    }
    return _locationArray;
}

- (NSMutableArray *)equipmentTypeArray{
    if (!_equipmentTypeArray) {
        _equipmentTypeArray = [self equipmentTypes];
    }
    return _equipmentTypeArray;
}

- (NSMutableArray *)equipmentTypes{
    NSMutableArray * equipmentMut = [NSMutableArray array];
    YWEquipmentType * equipmentType = [[YWEquipmentType alloc] init];
    equipmentType.equipmentTypeName = [NSString stringWithFormat:@"设备类型"];
    [equipmentMut addObject:equipmentType];
    
    NSArray * typeArray = [[YWEquipmentManager shareManager] equipmentTypesWithLocationId:_currentLocation.locationId orBuildingId:_currentBuilding.buildingId];
    [equipmentMut addObjectsFromArray:typeArray];
    return equipmentMut;
}

- (NSMutableArray *)tableViewDataSource{
    if (!_tableViewDataSource) {
        _tableViewDataSource = [NSMutableArray array];
        if (self.qrcodeId) {
            NSArray * equipments = [[YWEquipmentManager shareManager] equipmentInNoQrcodeLedgerWithQrcodeId:self.qrcodeId];
            [_tableViewDataSource addObjectsFromArray:equipments];
        }else if (self.locationId>0){
            YWLocation* location = [[YWBuildingManager shareManager] locationWithId:self.locationId];
            _currentLocation = location;
            _currentFloor = [[YWBuildingManager shareManager] floorWithId:location.floorId];
            _currentApartment = [[YWBuildingManager shareManager] apartmentWithId:_currentFloor.apartmentId];
            _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:self.locationId];
            NSArray *equipments = [[YWEquipmentManager shareManager] equipmentInfoArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId];
            
            [_tableViewDataSource addObjectsFromArray:equipments];
        }else{
            NSArray *equipments = [[YWEquipmentManager shareManager] equipmentInfoArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId];
            
            [_tableViewDataSource addObjectsFromArray:equipments];
        }
    }
    return _tableViewDataSource;
}

- (YWNoQrcodeLocationCellModel*)locationModel{
    if (!_locationModel) {
        //构建model
        YWNoQrcodeLocationCellModel * locationModel = [[YWNoQrcodeLocationCellModel alloc] init];
        _locationModel = locationModel;
    }
    return _locationModel;
}

- (void)setUpButton:(UIButton*)button{
    NSInteger count = self.matchMissions.count;
    NSString *countStr = @"";
    if (count > 0) {
        countStr = [NSString stringWithFormat:@"已匹配%lu条待执行的任务",(unsigned long)self.matchMissions.count];
        button.backgroundColor = [UIColor customBlueColor];
    }else{
        //        countStr = @"此二维码无待执行的任务";
        //        button.backgroundColor = [UIColor customTextGrayBlackColor];
        //        self.tableView.tableHeaderView.hidden = YES;
    }
    [button setTitle:countStr forState:UIControlStateNormal];
}

- (void)refreshMatchMissions{
    NSInteger count = [self.matchMissions count];
    if (self.qrcodeId) {
        NSArray *matchMission = [[YWMissionManager shareManager] matchAllTypeMissionsWithQrcodeId:self.qrcodeId];
        self.matchMissions = matchMission;
        [self setUpButton:self.headButton];
    }else{
        if (self.currentLocation.locationId) {
            NSArray *matchMission = [[YWMissionManager shareManager] matchAllTypeMissionsWithLocationId:self.currentLocation.locationId];
            self.matchMissions = matchMission;
            [self setUpButton:self.headButton];
        }else{
            self.matchMissions = nil;
        }
    }
    if (self.matchMissions.count==0 && _headButton) {
        [_headButton removeFromSuperview];
        if (count>0) {
            [self.tableView reloadData];
        }
    }
}

- (void)clickHeadViewButtonEvent:(id)sender{
    //点击headView,跳转匹配的任务列表
    if (self.matchMissions.count>0) {
        YWMatchMissionsViewController *matchMissionVC = [[YWMatchMissionsViewController alloc] init];
        matchMissionVC.matchMissions = self.matchMissions;
        matchMissionVC.qrCodeId = self.qrcodeId;
        matchMissionVC.locationId = self.currentLocation.locationId;
        [self.navigationController pushViewController:matchMissionVC animated:YES];
    }else{
        [YWCommonTool showTextHUDWithContent:@"此二维码无待执行的任务"];
    }
}

- (void)goSelect{
    [self.tableViewDataSource removeAllObjects];
    //给model赋值
    [self setUpModel:nil];
    //数据源
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentInfoArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId];
    
    [self.tableViewDataSource addObjectsFromArray:equipments];
    
    [self.tableView reloadData];
}

- (void)setUpModel:(NSString*)qrCodeId{
    self.locationModel.apartment = self.currentApartment;
    self.locationModel.floor = self.currentFloor;
    self.locationModel.location = self.currentLocation;
    self.locationModel.building = self.currentBuilding;
    NSInteger equipmentCount = 0;
    if (qrCodeId) {
        equipmentCount = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:self.qrcodeId].count;
        self.locationModel.qrcodeEquipments = 1;
    }else{
        equipmentCount = [[YWEquipmentManager shareManager] equipmentCountWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId];
        NSInteger qrcodeCount = [[YWEquipmentManager shareManager] qrcodeCountWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId];
        self.locationModel.qrcodeEquipments = qrcodeCount;
    }
    self.locationModel.equipmentCount = equipmentCount;
}

#pragma mark--- delegate of YWNoQrcodeLedgerLocationTableViewCell
-(void)clickLocationPostTroubleButtonEvent:(UITableViewCell*)cell{
    //需选择具体位置才能点击
    if (self.currentLocation.locationId) {
        YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdPostTrouble];
        if (function.offOrOn == YWFunctionStatusOn) {
            NSArray *allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:self.currentLocation.locationId];
            YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];
            postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;
            postTroublevc.equipmentArray = allEquipmentArray;
            postTroublevc.qrCodeId = _qrcodeId;
            postTroublevc.locationId = self.locationId;
            postTroublevc.shouldPopBack = YES;
            [self.navigationController pushViewController:postTroublevc animated:YES];
        }else{
            [self alartControllerWithString:@"报障"];
        }
    }else{
        [self alartControllerWithSelectLocationFirst];
    }
}

-(void)clickLocationMaintanceButtonEvent:(UITableViewCell*)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(YWNoQrcodeLedgerLocationTableViewCell*)cell];
    if (_currentLocation.locationId>0) {
        if (indexPath.section == 0) {
            BHBItem * Item1 = [[BHBItem alloc]initWithTitle:@"" Icon:@""];
            BHBItem * Item2 = [[BHBItem alloc]initWithTitle:@"" Icon:@""];
            BHBItem * Item3 = [[BHBItem alloc]initWithTitle:@"" Icon:@""];
            BHBItem * inspectionItem = [[BHBItem alloc]initWithTitle:@"巡查" Icon:@"profile_patrol"];
            BHBItem * keepWatchItem = [[BHBItem alloc]initWithTitle:@"巡更" Icon:@"patroling"];
            //添加popview
            [BHBPopView showToView:self.view.window withItems:@[Item1,Item2,Item3,keepWatchItem,inspectionItem] andSelectBlock:^(BHBItem *item) {
                if ([item isKindOfClass:[BHBGroup class]]) {
                    YWLog(@"选中%@分组",item.title);
                }else{
                    if ([item.title isEqualToString:@"巡查"]) {
                        YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdInspection];
                        if (function.offOrOn == YWFunctionStatusOn) {
                            //巡查任务
                            YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
                            tempMissionVC.locationId = self.locationId?:_currentLocation.locationId;
                            tempMissionVC.isLocationInspection = YES;
                            tempMissionVC.isEquipmentInspection = NO;
                            tempMissionVC.maintenanceType = YWMaintenanceTypePatrol;
                            [self.navigationController pushViewController:tempMissionVC animated:YES];
                        }else{
                            [self alartControllerWithString:@"巡查"];
                        }
                    }else if ([item.title isEqualToString:@"巡更"]){
                        //巡更任务
                        YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdKeepWatch];
                        if (function.offOrOn == YWFunctionStatusOn) {
                            YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
                            tempMissionVC.maintenanceType = YWMaintenanceTypeKeepWatch;
                            tempMissionVC.locationId = self.locationId?:_currentLocation.locationId;
                            [self.navigationController pushViewController:tempMissionVC animated:YES];
                        }else{
                            [self alartControllerWithString:@"巡更"];
                        }
                    }
                }
            }];
        }
    }
    else{
        if (indexPath.section == 0) {
            [self alartControllerWithSelectLocationFirst];
        }
    }
}

- (void)alartControllerWithString:(NSString*)function{
    NSString * message = [NSString stringWithFormat:@"功能已关闭。如需再次使用%@功能，您可从“设置-功能”中再次打开。",function];
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)alartControllerWithSelectLocationFirst{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:@"请先选择方位" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)clickLocationDetailButtonEvent:(UITableViewCell*)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(YWNoQrcodeLedgerLocationTableViewCell*)cell];
    if (_currentLocation.locationId>0) {
        if (indexPath.section == 0) {
            YWNoQrcodeLedgerLocationDetailViewController * locationDetailVC = [[YWNoQrcodeLedgerLocationDetailViewController alloc] init];
            locationDetailVC.locationId = self.currentLocation.locationId;
            locationDetailVC.qrcodeId = self.qrcodeId;
            [self.navigationController pushViewController:locationDetailVC animated:YES];
        }
    }
    else{
        if (indexPath.section == 0) {
            [self alartControllerWithSelectLocationFirst];
        }
    }
}

#pragma mark--- delegate of YWLedgerEquTypeTotalCellDelegate
-(void)clickEquTypePostTroubleButtonEvent:(UITableViewCell*)cell{
    if (self.currentLocation.locationId) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:(YWLedgerEquTypeTotalCell*)cell];
        YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdPostTrouble];
        if (function.offOrOn == YWFunctionStatusOn) {
            //当前设备类型的设备数组
//            NSArray *allEquipmentArray = self.tableViewDataSource[indexPath.section-1];
            YWQrcodeEquipmentInfo * equipmentInfo = self.tableViewDataSource[indexPath.section-1];
            NSArray *allEquipmentArray = [[YWEquipmentManager shareManager] equipmentArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:equipmentInfo.equipmentTypeId];
            YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];
            postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;
            postTroublevc.equipmentArray = allEquipmentArray;
            postTroublevc.qrCodeId = _qrcodeId;
            postTroublevc.locationId = self.locationId;
            postTroublevc.shouldPopBack = YES;
            [self.navigationController pushViewController:postTroublevc animated:YES];
        }else{
            [self alartControllerWithString:@"报障"];
        }
    }else{
        [self alartControllerWithSelectLocationFirst];
    }
}

-(void)clickEquTypeMaintanceButtonEvent:(UITableViewCell*)cell{
    if (self.currentLocation.locationId) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:(YWLedgerEquTypeTotalCell*)cell];
        YWQrcodeEquipmentInfo * equipmentInfo = self.tableViewDataSource[indexPath.section-1];
        NSArray *allEquipmentArray = [[YWEquipmentManager shareManager] equipmentArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:equipmentInfo.equipmentTypeId];
        YWEquipment * equipment = allEquipmentArray[0];
        BHBItem * inspectionItem = [[BHBItem alloc]initWithTitle:@"巡查" Icon:@"profile_patrol"];
        BHBItem * keepWatchItem = [[BHBItem alloc]initWithTitle:@"检测" Icon:@"profile_detection"];
        BHBItem * upkeepItem = [[BHBItem alloc]initWithTitle:@"保养" Icon:@"profile_upkeep"];
        BHBItem * repairItem = [[BHBItem alloc]initWithTitle:@"维修" Icon:@"profile_repair"];
        //添加popview
        [BHBPopView showToView:self.view.window withItems:@[inspectionItem,keepWatchItem,upkeepItem,repairItem] andSelectBlock:^(BHBItem *item) {
            if ([item isKindOfClass:[BHBGroup class]]) {
                
            }else{
                if ([item.title isEqualToString:@"巡查"]) {
                    //设备巡查
                    YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdInspection];
                    if (function.offOrOn == YWFunctionStatusOn) {
                        YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
                        tempMissionVC.maintenanceType = YWMaintenanceTypePatrol;
                        tempMissionVC.qrcodeId = equipment.qrcodeId;
                        tempMissionVC.locationId = equipment.locationId;
                        tempMissionVC.currentEquipmentId = equipment.equipmentId;
                        tempMissionVC.allEquArray = allEquipmentArray;
                        tempMissionVC.isLocationInspection = NO;
                        tempMissionVC.isEquipmentInspection = YES;
                        [self.navigationController pushViewController:tempMissionVC animated:YES];
                    }else{
                        [self alartControllerWithString:@"巡查"];
                    }
                }else if ([item.title isEqualToString:@"检测"]){
                    YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdDetection];
                    if (function.offOrOn == YWFunctionStatusOn) {
                        YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
                        tempMissionVC.qrcodeId = equipment.qrcodeId;
                        tempMissionVC.locationId = equipment.locationId;
                        tempMissionVC.allEquArray = allEquipmentArray;
                        tempMissionVC.currentEquipmentId = equipment.equipmentId;
                        tempMissionVC.maintenanceType = YWMaintenanceTypeDetection;
                        [self.navigationController pushViewController:tempMissionVC animated:YES];
                    }else{
                        [self alartControllerWithString:@"检测"];
                    }
                }else if ([item.title isEqualToString:@"保养"]){
                    YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdUpkeep];
                    if (function.offOrOn == YWFunctionStatusOn) {
                        YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
                        tempMissionVC.qrcodeId = equipment.qrcodeId;
                        tempMissionVC.locationId = equipment.locationId;
                        tempMissionVC.allEquArray = allEquipmentArray;
                        tempMissionVC.currentEquipmentId = equipment.equipmentId;
                        tempMissionVC.maintenanceType = YWMaintenanceTypeUpkeep;
                        [self.navigationController pushViewController:tempMissionVC animated:YES];
                    }else{
                        [self alartControllerWithString:@"保养"];
                    }
                }else if ([item.title isEqualToString:@"维修"]){
                    YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdRepair];
                    if (function.offOrOn == YWFunctionStatusOn) {
                        YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
                        tempMissionVC.maintenanceType = YWMaintenanceTypeTrouble;
                        tempMissionVC.equipment = equipment;
                        tempMissionVC.allEquArray = allEquipmentArray;
                        tempMissionVC.qrcodeId = equipment.qrcodeId;
                        [self.navigationController pushViewController:tempMissionVC animated:YES];
                    }else{
                       [self alartControllerWithString:@"维修"];
                    }
                }else{
                    //取消
                }
            }
        }];
    }else{
        [self alartControllerWithSelectLocationFirst];
    }
}

-(void)clickEquTypeDetailButtonEvent:(UITableViewCell*)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(YWLedgerEquTypeTotalCell*)cell];
//    YWEquipment * equipment = self.tableViewDataSource[indexPath.section-1][0];
    YWQrcodeEquipmentInfo * equipmentInfo = self.tableViewDataSource[indexPath.section-1];
    YWLedgerEquListTableViewController * equListVC = [[YWLedgerEquListTableViewController alloc] init];
    equListVC.equipmentTypeId = equipmentInfo.equipmentTypeId;
    equListVC.qrcodeId = self.qrcodeId;
    equListVC.locationModel = self.locationModel;
    [self.navigationController pushViewController:equListVC animated:YES];
}

#pragma mark - YWSelectBuildingTableViewControllerDelegate

- (void)rightBarButtonItemEvent:(id)sender{
    //选择楼盘
    YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
    selectBuildingVC.delegate = self;
    selectBuildingVC.ownBuilding = _currentBuilding;
    [self.navigationController pushViewController:selectBuildingVC animated:YES];
}

-(void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![self.currentBuilding.buildingId isEqualToString:building.buildingId]) {
        //将选中的楼盘赋给当前楼盘，楼栋、楼层、位置等全部置空
        self.currentBuilding = building;
        _currentApartment = nil;
        _currentFloor = nil;
        _currentLocation = nil;
        _currentEquipmentType = nil;
        self.apartmentArray = nil;
        self.floorArray = nil;
        self.locationArray = nil;
        self.equipmentTypeArray = nil;
        self.qrcodeId = nil;
        [self.navigationItem.rightBarButtonItem setTitle:_currentBuilding.buildingName];
        [self defaultData];
        [self goSelect];
        [self refreshMatchMissions];
        [self.menu reloadData];
        [self.tableView reloadData];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
